package darwin8086.genetic;

import darwin8086.war.*;
import java.io.*;

public class Algorithm {
	
	private Competition competition;
	final int battlesPerGroup;
	final int generationSize;
	final int botSize;
	final int fightsPerGeneration;
	final int mutationRate;
	final MutationOp op;
	final String id;
	
	/**
	 * @param args
	 */
	
	public Algorithm(String newID,int newGenerationSize, int newBattlesPerGroup, int newBotSize, int newFightsPerGen,
			int newMutationRate, MutationOp newOp) throws IOException{
		id = newID;
		battlesPerGroup = newBattlesPerGroup;
		generationSize = newGenerationSize;
		botSize = newBotSize;
		competition = new Competition();
		competition.setSpeed(2147483647); //maximum speed
		fightsPerGeneration = newFightsPerGen;
		mutationRate = newMutationRate;
		op = newOp;
		CreateDir(id);
		/*****delete files from survivors folder*****/
	}
	
	public void CreateDir(String dir){
		File dirFile  = new File("results/" + dir);
		dirFile.mkdirs();		
	}
	
	public void Run(int iterations) throws Exception{
		Benchmarker benchmarker = new Benchmarker(generationSize,iterations);
		try {
			Generation generation = new Generation("results/" + id,generationSize,botSize,op);
			
			for(int i=0;i<iterations;i++) {
				System.out.println("started generation:" + i);
				for(int j=0;j<fightsPerGeneration;j++) {
					generation.WriteToBots();
					System.out.println("started fight:" + j);
					try {
						competition = new Competition();
						competition.setSpeed(2147483647); //maximum int value possible
						competition.runCompetition(battlesPerGroup,
								botSize);						
					} catch (Exception e) {
						e.printStackTrace();
					}
					generation.UpdateAllFitness(competition.getWarriorRepository());
					System.out.println("done fight");
				}
				System.out.println("done generation");
				System.out.println("benchmarking");
				benchmarker.BenchmarkGeneration(generation);
				System.out.println("done benchmarking");
				generation.WriteFitnessReport("Generation_" + i + ".csv");
				generation.Mutate(mutationRate);
			}
			generation.WriteFitnessReport("final.csv");
			generation.WriteAll();
			
		} catch (NumberFormatException e2) {
			// do nothing
		}
		benchmarker.StatisticsOut("Run");
	}
	
	public static void main(String[] args) throws Exception {
		
		try{
			Algorithm algo = new Algorithm("General_Inst.RMUTATION.128.5.4.64.64.NewChoice",128,5,4,64,64,MutationOp.RMUTATION);
			long runningTime = System.currentTimeMillis();
			algo.Run(250);
			runningTime = System.currentTimeMillis() - runningTime;
			runningTime /= 1000; //convert from milliseconds to seconds
			System.out.println("running time: " + runningTime + "seconds");
		} catch(IOException e){
			//do nothing
		}

		System.exit(0);
	}

}
